package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.dto.AcceptanceChecklistSubmitDTO;
import com.ruoyi.system.entity.AcceptanceChecklistInstanceDO;
import com.ruoyi.system.entity.AcceptanceChecklistRecordDO;
import com.ruoyi.system.mapper.AcceptanceChecklistInstanceMapper;
import com.ruoyi.system.mapper.AcceptanceChecklistItemMapper;
import com.ruoyi.system.mapper.AcceptanceChecklistRecordMapper;
import com.ruoyi.system.service.AcceptanceChecklistInstanceService;
import com.ruoyi.system.service.AcceptanceChecklistTemplateService;
import com.ruoyi.system.vo.AcceptanceChecklistInstanceVO;
import com.ruoyi.system.vo.AcceptanceChecklistTemplateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 验收单实例服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
public class AcceptanceChecklistInstanceServiceImpl implements AcceptanceChecklistInstanceService {

    @Resource
    private AcceptanceChecklistInstanceMapper instanceMapper;

    @Resource
    private AcceptanceChecklistItemMapper itemMapper;

    @Resource
    private AcceptanceChecklistRecordMapper recordMapper;

    @Resource
    private AcceptanceChecklistTemplateService templateService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createInstance(Long templateId, Long projectId, Long stageId, Long h5UserId, String h5UserName, Long msgTaskId, Long msgItemId) {
        // 获取模板信息
        AcceptanceChecklistTemplateVO template = templateService.getTemplateDetail(templateId);
        if (template == null) {
            throw new RuntimeException("验收单模板不存在");
        }

        // 创建实例
        AcceptanceChecklistInstanceDO instance = new AcceptanceChecklistInstanceDO();
        instance.setTemplateId(templateId);
        instance.setProjectId(projectId);
        instance.setStageId(stageId);
        instance.setInstanceName(template.getTemplateName());
        instance.setMsgTaskId(msgTaskId);
        instance.setMsgItemId(msgItemId);
        instance.setH5UserId(h5UserId);
        instance.setH5UserName(h5UserName);
        instance.setStatus("PENDING");
        instance.setCreateBy(SecurityUtils.getUsername());
        instance.setCreateTime(LocalDateTime.now());
        instanceMapper.insert(instance);

        // 创建填写记录
        for (AcceptanceChecklistTemplateVO.TemplateItemVO item : template.getItems()) {
            AcceptanceChecklistRecordDO record = new AcceptanceChecklistRecordDO();
            record.setInstanceId(instance.getId());
            record.setTemplateItemId(item.getId());
            record.setSeqNo(item.getSeqNo());
            record.setItemName(item.getItemName());
            record.setAcceptanceStandard(item.getAcceptanceStandard());
            record.setAcceptanceType(item.getAcceptanceType());
            record.setIsCompleted(0);
            record.setCreateBy(SecurityUtils.getUsername());
            record.setCreateTime(LocalDateTime.now());
            recordMapper.insert(record);
        }

        return instance.getId();
    }

    @Override
    public AcceptanceChecklistInstanceVO getInstanceDetail(Long instanceId) {
        // 查询实例
        AcceptanceChecklistInstanceDO instance = instanceMapper.selectById(instanceId);
        if (instance == null) {
            return null;
        }

        // 查询模板信息
        AcceptanceChecklistTemplateVO template = templateService.getTemplateDetail(instance.getTemplateId());

        // 查询填写记录
        LambdaQueryWrapper<AcceptanceChecklistRecordDO> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(AcceptanceChecklistRecordDO::getInstanceId, instanceId)
                .orderByAsc(AcceptanceChecklistRecordDO::getSeqNo);
        List<AcceptanceChecklistRecordDO> records = recordMapper.selectList(recordWrapper);

        // 转换为VO
        AcceptanceChecklistInstanceVO vo = new AcceptanceChecklistInstanceVO();
        BeanUtils.copyProperties(instance, vo);
        vo.setTemplate(template);

        List<AcceptanceChecklistInstanceVO.RecordVO> recordVOs = records.stream()
                .map(record -> {
                    AcceptanceChecklistInstanceVO.RecordVO recordVO = new AcceptanceChecklistInstanceVO.RecordVO();
                    BeanUtils.copyProperties(record, recordVO);
                    
                    // 解析图片URL列表
                    if (record.getCompletionImages() != null) {
                        try {
                            List<String> images = objectMapper.readValue(record.getCompletionImages(), new TypeReference<List<String>>() {});
                            recordVO.setCompletionImages(images);
                        } catch (Exception e) {
                            // 忽略解析错误
                        }
                    }
                    
                    return recordVO;
                })
                .collect(Collectors.toList());
        vo.setRecords(recordVOs);

        return vo;
    }

    @Override
    public AcceptanceChecklistInstanceVO getInstanceByMsgItemId(Long msgItemId) {
        LambdaQueryWrapper<AcceptanceChecklistInstanceDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AcceptanceChecklistInstanceDO::getMsgItemId, msgItemId);
        AcceptanceChecklistInstanceDO instance = instanceMapper.selectOne(wrapper);
        
        if (instance == null) {
            return null;
        }
        
        return getInstanceDetail(instance.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitChecklist(AcceptanceChecklistSubmitDTO submitDTO) {
        // 查询实例
        AcceptanceChecklistInstanceDO instance = instanceMapper.selectById(submitDTO.getInstanceId());
        if (instance == null) {
            throw new RuntimeException("验收单实例不存在");
        }

        // 更新填写记录
        for (AcceptanceChecklistSubmitDTO.RecordDTO recordDTO : submitDTO.getRecords()) {
            LambdaQueryWrapper<AcceptanceChecklistRecordDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AcceptanceChecklistRecordDO::getInstanceId, submitDTO.getInstanceId())
                    .eq(AcceptanceChecklistRecordDO::getTemplateItemId, recordDTO.getTemplateItemId());
            
            AcceptanceChecklistRecordDO record = recordMapper.selectOne(wrapper);
            if (record != null) {
                record.setIsCompleted(recordDTO.getIsCompleted());
                record.setCompletionRemark(recordDTO.getCompletionRemark());
                
                // 序列化图片URL列表
                if (recordDTO.getCompletionImages() != null && !recordDTO.getCompletionImages().isEmpty()) {
                    try {
                        String imagesJson = objectMapper.writeValueAsString(recordDTO.getCompletionImages());
                        record.setCompletionImages(imagesJson);
                    } catch (Exception e) {
                        throw new RuntimeException("图片URL序列化失败", e);
                    }
                }
                
                if (recordDTO.getIsCompleted() == 1) {
                    record.setCompletionTime(LocalDateTime.now());
                }
                
                record.setUpdateBy(SecurityUtils.getUsername());
                record.setUpdateTime(LocalDateTime.now());
                recordMapper.updateById(record);
            }
        }

        // 更新实例状态
        instance.setStatus("COMPLETED");
        instance.setSubmitTime(LocalDateTime.now());
        instance.setUpdateBy(SecurityUtils.getUsername());
        instance.setUpdateTime(LocalDateTime.now());
        instanceMapper.updateById(instance);

        return true;
    }

    @Override
    public List<AcceptanceChecklistInstanceVO> getInstancesByH5UserId(Long h5UserId, String status) {
        LambdaQueryWrapper<AcceptanceChecklistInstanceDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AcceptanceChecklistInstanceDO::getH5UserId, h5UserId)
                .eq(status != null, AcceptanceChecklistInstanceDO::getStatus, status)
                .orderByDesc(AcceptanceChecklistInstanceDO::getCreateTime);
        
        List<AcceptanceChecklistInstanceDO> instances = instanceMapper.selectList(wrapper);
        
        return instances.stream()
                .map(instance -> getInstanceDetail(instance.getId()))
                .collect(Collectors.toList());
    }

    @Override
    public List<AcceptanceChecklistInstanceVO> getInstancesByProjectStage(Long projectId, Long stageId) {
        LambdaQueryWrapper<AcceptanceChecklistInstanceDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AcceptanceChecklistInstanceDO::getProjectId, projectId)
                .eq(AcceptanceChecklistInstanceDO::getStageId, stageId)
                .orderByDesc(AcceptanceChecklistInstanceDO::getCreateTime);
        
        List<AcceptanceChecklistInstanceDO> instances = instanceMapper.selectList(wrapper);
        
        return instances.stream()
                .map(instance -> getInstanceDetail(instance.getId()))
                .collect(Collectors.toList());
    }
}
